package com.java.interview.string;

/**
 * Created by lyc on 2016-03-23.
 */
//String、StringBuffer与StringBuilder之间区别?
//String是不可变的，StringBuffer是可变的；StringBuffer是线程安全的，StringBuilder是非线程安全的。
//因而在大部分情况下字符串的拼接速度为：StringBuilder>StringBuffer>String
public class InterviewStringBuffer {
    //小结：如果对字符串中的内容经常进行操作，特别是内容要修改时，那么使用StringBuffer，如果最后需要String，那么使用StringBuffer的toString()方法进行转换
    public static void main(String[] args){
        InterviewStringBuffer inter=   new InterviewStringBuffer();
        inter.testString();//长度不可变
        inter.testStringBuffer();//长度可变，线程安全
        inter.testStringBuilder();//长度可变，线程不安全
    }

    public void testString(){
        long startTime = System.currentTimeMillis();
        long startMem = Runtime.getRuntime().freeMemory();
        String str="";
        for (int i=0; i<1000; i++) {
            str += "a";
        }
        long endMem = Runtime.getRuntime().freeMemory();
        System.out.println("String Use memory: "+ (startMem - endMem));//String Use memory: 127760
        long endTime = System.currentTimeMillis();
        System.out.println("String Use Time: "+ (endTime-startTime));
        System.out.println("--------------------------------------------");//String Use Time: 15
    }

    public void testStringBuffer(){
        StringBuffer sb = new StringBuffer();
        long startTime = System.currentTimeMillis();
        long startMem = Runtime.getRuntime().freeMemory();
        for (int i=0; i<1000; i++) {
            sb.append("a");// public synchronized StringBuffer append
        }
        long endMem = Runtime.getRuntime().freeMemory();//StringBuffer Use memory: 0
        System.out.println("StringBuffer Use memory: "+ (startMem - endMem));
        long endTime = System.currentTimeMillis();//StringBuffer Use Time: 1
        System.out.println("StringBuffer Use Time: "+ (endTime-startTime));
        System.out.println("*********************************************");
    }

    public void testStringBuilder(){
        StringBuilder sbd = new StringBuilder();
        //public final class StringBuilde extends AbstractStringBuilder
        // implements java.io.Serializable, CharSequence
        long startTime = System.currentTimeMillis();
        long startMem = Runtime.getRuntime().freeMemory();
        for (int i=0; i<1000; i++) {
            sbd.append("a");//public StringBuilder append(String str)
        }
        long endMem = Runtime.getRuntime().freeMemory();//StringBuilder Use memory: 0
        System.out.println("StringBuilder Use memory: "+ (startMem - endMem));
        long endTime = System.currentTimeMillis();//StringBuilder Use Time: 0
        System.out.println("StringBuilder Use Time: "+ (endTime-startTime));
    }
}
